﻿// ----------------------------------------------------------------------------------
// Microsoft Developer & Platform Evangelism
// 
// Copyright (c) Microsoft Corporation. All rights reserved.
// 
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES 
// OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// ----------------------------------------------------------------------------------
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
// ----------------------------------------------------------------------------------

namespace umbraco.ACSExtensions
{
    using System;
    using System.Globalization;
    using System.Net.Mail;
    using System.Web;
    using umbraco.cms.businesslogic;
    using umbraco.cms.businesslogic.member;

    public class FederatedMembersInvitationModule : IHttpModule
    {
        private static object activationLock = new object();

        public void Init(HttpApplication context)
        {
            // Only subscribe to New Member event if SMTP is configured correctly
            if (ACSExtensionsSettings.ValidSmtp())
            {
                Member.New += new Member.NewEventHandler(this.Member_New);
            }
        }

        public void Dispose()
        {
        }

        internal void Member_New(Member sender, NewEventArgs e)
        {
            // Only for Federated Members (Member Type)
            if (ACSExtensionsSettings.SocialMemberType == null ||
                !sender.ContentType.Alias.Equals(ACSExtensionsSettings.SocialMemberType.Alias, StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            lock (activationLock)
            {
                var invitationSent = sender.GetGenericProperty<bool>(ACSExtensionsSettings.MemberInvitationSentPropertyAlias);

                if (!invitationSent)
                {
                    var activationEmailMessage = HttpContext.Current.Session["activationEmailMessage"];
                    if (activationEmailMessage != null)
                    {
                        HttpContext.Current.Session.Remove("activationEmailMessage");

                        var ticketNumber = sender.UniqueId;
                        var activationLink = GenerateActivationLink(ticketNumber);

                        var notificationTemplate = string.IsNullOrWhiteSpace(activationEmailMessage.ToString()) ?
                            ACSExtensionsSettings.ActivationEmailTemplateBody :
                            activationEmailMessage.ToString();

                        var notification = notificationTemplate.Replace(
                            "{activationUrl}",
                            string.Format(CultureInfo.InvariantCulture, "<a target=\"_blank\" href=\"{0}\">{0}</a>", activationLink));

                        SendNotification(
                            ACSExtensionsSettings.ActivationSenderAddress,
                            ACSExtensionsSettings.ActivationSenderName,
                            sender.Email,
                            ACSExtensionsSettings.ActivationEmailSubject,
                            notification);

                        sender.SetGenericProperty(ACSExtensionsSettings.MemberInvitationSentPropertyAlias, bool.TrueString);
                        sender.Save();
                    }
                    else
                    {
                        if (!sender.GetGenericProperty<bool>(ACSExtensionsSettings.MemberInvitationSentPropertyAlias))
                        {
                            sender.SetGenericProperty(ACSExtensionsSettings.MemberInvitationSentPropertyAlias, bool.FalseString);
                        }
                    }
                }

                sender.SetGenericProperty(ACSExtensionsSettings.MemberIsActivatedPropertyAlias, bool.FalseString);
            }
        }

        private static void SendNotification(string fromAddress, string fromDisplayName, string destinationAddress, string title, string message)
        {
            using (var smtpClient = new SmtpClient())
            {
                using (var mailMessage = new MailMessage())
                {
                    mailMessage.From = new MailAddress(fromAddress, fromDisplayName);
                    mailMessage.Subject = title;
                    mailMessage.Body = message;
                    mailMessage.IsBodyHtml = true;
                    mailMessage.To.Add(new MailAddress(destinationAddress));

                    smtpClient.Send(mailMessage);
                }
            }
        }

        private string GenerateActivationLink(Guid ticketNumber)
        {
            return ACSExtensionsSettings.GetAppDomainAddress() + ACSExtensionsSettings.GenerateActivationUrl(ticketNumber);
        }
    }
}